package com.ying.tests.AAAVIP;

import java.io.FileInputStream;
import java.lang.reflect.Method;

/**
 * 模拟Tomcat打破双亲委派规则
 */
public class TomcatBreakMyClassLoader extends ClassLoader {

    private String classPath;

    public TomcatBreakMyClassLoader(String classPath) {
    this.classPath = classPath;
    }

    /**
     * 将.class文件存放的路径拼接完整，如：D:/项目地址/包路径/xxx.class
     */
    private byte[] loadByte(String name) throws Exception {
        name = name.replaceAll("\\.", "/");
        FileInputStream fileIn = new FileInputStream(classPath + "/" + name + ".class");
        int len = fileIn.available();
        byte[] data = new byte[len];
        fileIn.read(data);
        fileIn.close();
        return data;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] data = loadByte(name);
            // defineClass将一个字节数组转为Class对象，这个字节数组是class文件读取后最终的字节数组。
            return defineClass(name, data, 0, data.length);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ClassNotFoundException();
        }
    }

    /**
     * 此方法就是双亲委派规则的核心方法，我们进行重写，不委派给双亲加载
     */
    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        synchronized (getClassLoadingLock(name)) {
            // First, check if the class has already been loaded
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                // If still not found, then invoke findClass in order
                // to find the class.

                // 有一些如果不是我们的User路径就去父类加载器去加载 如：java.lang.Object、String、System、java.io.PrintStream
                if (!name.startsWith("com.ying.tests.AAAVIP.User")) {
                    c = this.getParent().loadClass(name);
                }else {
//                    long t1 = System.nanoTime();
                    c = findClass(name);
                    // this is the defining class loader; record the stats
//                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
//                    sun.misc.PerfCounter.getFindClasses().increment();
                }
            }
            if (resolve) {
                resolveClass(c);
            }
            return c;
        }
    }

    public static void main(String[] args) throws Exception {
        // 模拟web1
        TomcatBreakMyClassLoader web1 = new TomcatBreakMyClassLoader("D:/Work/IdeaProjects/Vipkid/my/tests");
        Class clazz1 = web1.loadClass("com.ying.tests.AAAVIP.User");
        Object obj1 = clazz1.newInstance();
        Method method1 = clazz1.getDeclaredMethod("login", new Class[0]);
        method1.setAccessible(true);
        method1.invoke(obj1, new Object[]{});
        System.out.println(clazz1.getClassLoader().getClass().getName());

        // 模拟web2
        TomcatBreakMyClassLoader web2 = new TomcatBreakMyClassLoader("D:/Work/IdeaProjects/Vipkid/my/tests2");
        Class clazz2 = web2.loadClass("com.ying.tests.AAAVIP.User");
        Object obj2 = clazz2.newInstance();
        Method method2 = clazz2.getDeclaredMethod("login", new Class[0]);
        method2.setAccessible(true);
        method2.invoke(obj2, new Object[]{});
        System.out.println(clazz2.getClassLoader().getClass().getName());

    }
}
